package marketPlace;

import general.AuctionOptions;
import general.MarketPlaceMarketeerInterface;
import general.Product;
import general.ProductPrice;
import general.ProductRecord;
import general.ProductRequest;

import java.rmi.RemoteException;
import java.sql.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.UUID;

import net.jini.core.lookup.ServiceItem;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.core.transaction.Transaction;
import net.jini.core.transaction.Transaction.Created;
import net.jini.core.transaction.TransactionFactory;
import net.jini.core.transaction.server.TransactionManager;
import net.jini.discovery.LookupDiscoveryManager;
import net.jini.lease.LeaseRenewalManager;
import net.jini.lookup.ServiceDiscoveryManager;
import net.jini.space.JavaSpace;

public class MarketPlaceMarketeerService implements MarketPlaceMarketeerInterface {
	
	private MarketPlace fMarketPlace;
	private JavaSpace fJavaSpace;
	private TransactionManager fTransactionMgr;
	
	public MarketPlaceMarketeerService(MarketPlace marketPlace) throws RemoteException {
		fMarketPlace = marketPlace;
		fJavaSpace = fMarketPlace.getSpace();
		fTransactionMgr = fMarketPlace.getTransactionManager();
	}

	public void addProduct(Product product, AuctionOptions auctionOptions) throws RemoteException {
		// Give Product an ID and create productRecord
		product.setId(UUID.randomUUID());
		ProductRecord productRecord = new ProductRecord(product, auctionOptions, ProductRecord.STATE_WAITING);
		
		// Check whether product should be auctioned
		if (auctionOptions.getStartTime().before(new Date(System.currentTimeMillis()))) {
			
			// Add productRecord
			productRecord.setState(ProductRecord.STATE_AUCTIONING);
			fMarketPlace.addProductRecord(productRecord);
			System.out.println("Product added");
	           
			try {
				// Initialize transaction
				Created created = TransactionFactory.create(fTransactionMgr, 5000);
				Transaction transaction = created.transaction;
	        
		        // Create and write request into space
				ProductRequest productRequest = new ProductRequest(product.getId(), auctionOptions.getEndTime(), new ProductPrice(auctionOptions.getMinimumPrice()));
		        fJavaSpace.write(productRequest, transaction, 24*60*60);
		        transaction.commit();
		        
		        System.out.println("Product placed in auction space");
		        
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		// Otherwise, place request in queue
		} else {
			// Add productRecord
			fMarketPlace.addProductRecord(productRecord);
			System.out.println("Product added");
			
			// Place product in auction queue
			fMarketPlace.addToAuctionQueue(productRecord);
			System.out.println("Product added to auction queue");
		}
	}

	public LinkedList<ProductRecord> searchProducts(String name) throws RemoteException {		
		return fMarketPlace.searchProducts(name);
	}
}
